package utils

import (
	"fmt"
	"github.com/dgrijalva/jwt-go/v4"
)

var mySigningKey = []byte("wm_2023/11/10")

type MyCustomClaims struct {
	UserId int64 `json:"foo"`
	jwt.StandardClaims
}

// CreateToken 生成token
func CreateToken(claims *MyCustomClaims) string {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	ss, err := token.SignedString(mySigningKey)
	fmt.Printf("%v %v", ss, err)
	return ss
}

// ParseToken 验证token
func ParseToken(text string) (int64, int64) {
	token, err := jwt.ParseWithClaims(text, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
		return mySigningKey, nil
	})

	if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid {
		fmt.Printf("%v %v", claims.UserId, claims.StandardClaims.ExpiresAt.Unix())
		return claims.UserId, claims.StandardClaims.ExpiresAt.Unix()
	} else {
		fmt.Println(err)
		return 0, 0
	}
}
